<?php

class TextDealer
{
	static $_instance = null;
	static function getInstance()
	{
		if( self::$_instance === null )
		{
			self::$_instance = new self();
		}
		return self::$_instance;
	}

	function deal( &$str )
	{
		$arr = array(
			array('from'=>'/\s{2,}/', 'to'=>' '),
		);

		foreach( $arr as $one )
		{
			$str = preg_replace( $one['from'], $one['to'], $str );
		}
	}

	function convertEncodingStyle( $file )
	{
		$str = file_get_contents( $file );
		$encode = mb_detect_encoding($str, array('ASCII','UTF-8','GB2312','GBK','BIG5'));
		var_dump($encode);
		if( $encode != 'utf-8' && $encode != 'UTF-8' )
		{   
			$str = iconv( "gbk//IGNORE", "utf-8//IGNORE", $str );
		}   
		file_put_contents( $file, $str );
	}

	function downloadUrl( $url, $breget=false )
	{
		$file = BASE_PATH.'/img/'.substr($url, -11).'_'.md5($url);

		if( $breget && is_file( $file ) )
		{
			unlink( $file );
		} 

		if( !is_file( $file ) )
		{
			system("C:/Windows/wgetwin-1_5_3_1-binary/wget.exe {$url} -O {$file}");
			$stime = 5;
			while( !is_file( $file ) && $stime-- > 0 )
			{
				echo "wait for img\n";
				sleep(1);
			}
			
			if( !is_file( $file ) )
			{
				echo "download failed.".$url;
				return false;
			}
		}

		if( !is_file( $file ) )
		{
			return false;
		} 
		else
		{
			return $file;
		}
	}

}

if( isset($argv) && isset($argv[0]) && $argv[0] == basename(__FILE__))
{
	$obj = TextDealer::getInstance();
	$url = 'www.baidu.com';
	$r = $obj->downloadUrl($url);
	echo $r."\n";
}
